package com.ruoyi.web.controller.fs;

import java.net.URLDecoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SortListUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.fs.domain.*;
import com.ruoyi.fs.service.*;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.controller.tool.OSSUtil;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 案件进展开庭Controller
 *
 * @author hero
 * @date 2024-11-27
 */
@RestController
@RequestMapping("/fs/opencourt")
public class FsCaseProgressCourtController extends BaseController {
    @Autowired
    private IFsCaseService fsCaseService;
    @Autowired
    private IFsCaseProgressService fsCaseProgressService;
    @Autowired
    private IFsCaseProgressFileService fsCaseProgressFileService;
    @Autowired
    private IFsCaseProgressCourtService fsCaseProgressCourtService;
    @Autowired
    private IFsClientService fsClientService;
    @Autowired
    private IFsEntrustService fsEntrustService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private OSSUtil ossUtil;

    /**
     * 查询案件进展开庭列表
     */
    @PreAuthorize("@ss.hasPermi('fs:case:list')")
    @GetMapping("/list")
    public TableDataInfo list(FsCaseProgressCourt fsCaseProgressCourt) {
        Map<Long, String> zfMap = new HashMap<>();
        List<FsEntrust> entrusts = fsEntrustService.selectFsEntrustList(new FsEntrust());
        for (int i = 0; i < entrusts.size(); i++) {
            zfMap.put(entrusts.get(i).getId(), entrusts.get(i).getName());
        }
        Map<Long, String> userMap = new HashMap<>();
        List<SysUser> users = sysUserService.selectUserList(new SysUser());
        for (int i = 0; i < users.size(); i++) {
            userMap.put(users.get(i).getUserId(), users.get(i).getNickName());
        }
        startPage();
        List<FsCaseProgressCourt> list = fsCaseProgressCourtService.selectFsCaseProgressCourtList(fsCaseProgressCourt);
        for (int i = 0; i < list.size(); i++) {
            FsCaseProgressCourt progressCourt = list.get(i);
            FsCase fsCase = fsCaseService.selectFsCaseById(progressCourt.getCaseId());
            FsClient bg = fsClientService.selectFsClientById(fsCase.getBg());
            fsCase.setBgDsr(bg);
            if (fsCase.getZfid() != null) {
                fsCase.setZfName(zfMap.get(fsCase.getZfid()));
            }
            progressCourt.setFsCase(fsCase);
            if (progressCourt.getTjy() != null) {
                progressCourt.setTjyMc(userMap.get(progressCourt.getTjy()));
            }
            FsCaseProgressFile fileQuery = new FsCaseProgressFile();
            fileQuery.setProcessId(progressCourt.getProcessId());
            List<FsCaseProgressFile> lsFiles = null;
            List<FsCaseProgressFile> ktFiles = null;
            List<FsCaseProgressFile> qtFiles = null;

            List<FsCaseProgressFile> files = fsCaseProgressFileService.selectFsCaseProgressFileList(fileQuery);
            if (!files.isEmpty()) {
                for (int j = 0; j < files.size(); j++) {
                    FsCaseProgressFile file = files.get(j);
                    if (file.getType() == 1) {
                        if (lsFiles == null) {
                            lsFiles = new ArrayList<>();
                        }
                        lsFiles.add(file);
                    }
                    if (file.getType() == 2) {
                        if (ktFiles == null) {
                            ktFiles = new ArrayList<>();
                        }
                        ktFiles.add(file);
                    }
                    if (file.getType() == 3) {
                        if (qtFiles == null) {
                            qtFiles = new ArrayList<>();
                        }
                        qtFiles.add(file);
                    }
                }
            }
            progressCourt.setLsFiles(lsFiles);
            progressCourt.setKtFiles(ktFiles);
            progressCourt.setQtFiles(qtFiles);
        }
        return getDataTable(list);
    }

    /**
     * 导出案件进展开庭列表
     */
    @PreAuthorize("@ss.hasPermi('fs:case:export')")
    @Log(title = "案件进展开庭", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, FsCaseProgressCourt fsCaseProgressCourt) {
        List<FsCaseProgressCourt> list = fsCaseProgressCourtService.selectFsCaseProgressCourtList(fsCaseProgressCourt);
        ExcelUtil<FsCaseProgressCourt> util = new ExcelUtil<FsCaseProgressCourt>(FsCaseProgressCourt.class);
        util.exportExcel(response, list, "案件进展开庭数据");
    }

    /**
     * 获取案件进展开庭详细信息
     */
    @PreAuthorize("@ss.hasPermi('fs:case:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        FsCaseProgressCourt progressCourt = fsCaseProgressCourtService.selectFsCaseProgressCourtById(id);
        FsCase fsCase = fsCaseService.selectFsCaseById(progressCourt.getCaseId());
        FsClient bg = fsClientService.selectFsClientById(fsCase.getBg());
        fsCase.setBgDsr(bg);
        if (fsCase.getZfid() != null) {
            FsEntrust entrust = fsEntrustService.selectFsEntrustById(fsCase.getZfid());
            fsCase.setZfName(entrust.getName());
        }
        progressCourt.setFsCase(fsCase);
        FsCaseProgressFile fileQuery = new FsCaseProgressFile();
        fileQuery.setProcessId(progressCourt.getProcessId());
        List<FsCaseProgressFile> lsFiles = null;
        List<FsCaseProgressFile> ktFiles = null;
        List<FsCaseProgressFile> qtFiles = null;

        List<FsCaseProgressFile> files = fsCaseProgressFileService.selectFsCaseProgressFileList(fileQuery);
        if (!files.isEmpty()) {
            for (int j = 0; j < files.size(); j++) {
                FsCaseProgressFile file = files.get(j);
                if (file.getType() == 1) {
                    if (lsFiles == null) {
                        lsFiles = new ArrayList<>();
                    }
                    lsFiles.add(file);
                }
                if (file.getType() == 2) {
                    if (ktFiles == null) {
                        ktFiles = new ArrayList<>();
                    }
                    ktFiles.add(file);
                }
                if (file.getType() == 3) {
                    if (qtFiles == null) {
                        qtFiles = new ArrayList<>();
                    }
                    qtFiles.add(file);
                }
            }
        }
        progressCourt.setLsFiles(lsFiles);
        progressCourt.setKtFiles(ktFiles);
        progressCourt.setQtFiles(qtFiles);
        return success(progressCourt);
    }

    /**
     * 新增案件进展开庭
     */
    @PreAuthorize("@ss.hasPermi('fs:case:add')")
    @Log(title = "案件进展开庭", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody FsCaseProgressCourt fsCaseProgressCourt) {
        FsCaseProgress old = new FsCaseProgress();
        old.setCaseId(fsCaseProgressCourt.getCaseId());
        old.setJzlx(fsCaseProgressCourt.getJzlx());
        List<FsCaseProgress> progresses = fsCaseProgressService.selectFsCaseProgressList(old);
        if (!progresses.isEmpty()) {
            old = progresses.get(0);
            fsCaseProgressCourt.setProcessId(old.getId());
        }
        LoginUser loginUser = getLoginUser();
        if (fsCaseProgressCourt.getProcessId() == null) {
            FsCaseProgress progress = new FsCaseProgress();
            progress.setJzlx(fsCaseProgressCourt.getJzlx());
            progress.setCaseId(fsCaseProgressCourt.getCaseId());
            progress.setCjr(loginUser.getUserId());
            progress.setRq(fsCaseProgressCourt.getKtrq());
            progress.setCreateBy(loginUser.getUser().getNickName());
            progress.setRemark(fsCaseProgressCourt.getRemark());
            fsCaseProgressService.insertFsCaseProgress(progress);
            fsCaseProgressCourt.setProcessId(progress.getId());
        }
        FsCaseProgressCourt oldPC = new FsCaseProgressCourt();
        oldPC.setProcessId(fsCaseProgressCourt.getProcessId());
        List<FsCaseProgressCourt> oldPCs = fsCaseProgressCourtService.selectFsCaseProgressCourtList(oldPC);
        if (!oldPCs.isEmpty()) {
            fsCaseProgressCourt.setId(oldPCs.get(0).getId());
            fsCaseProgressCourt.setUpdateBy(loginUser.getUser().getNickName());
            fsCaseProgressCourtService.updateFsCaseProgressCourt(fsCaseProgressCourt);
        } else {
            FsCase fsCase = fsCaseService.selectFsCaseById(fsCaseProgressCourt.getCaseId());
            fsCaseProgressCourt.setFyid(fsCase.getFyid());
            fsCaseProgressCourt.setFymc(fsCase.getFymc());
            fsCaseProgressCourt.setTjy(fsCase.getTjyId());
            fsCaseProgressCourt.setCreateBy(loginUser.getUser().getNickName());
            fsCaseProgressCourtService.insertFsCaseProgressCourt(fsCaseProgressCourt);
        }

        return success();
    }

    private String getFileNameByUrl(String url) {
        url = URLDecoder.decode(url);
        url = url.split("\\?")[0];
        System.out.println(url);
        int index = url.lastIndexOf("/") + 1;
        String fileName = url.substring(index, url.length());
        return fileName;
    }

    /**
     * 修改案件进展开庭
     */
    @PreAuthorize("@ss.hasPermi('fs:case:edit')")
    @Log(title = "案件进展开庭", businessType = BusinessType.UPDATE)
    @PutMapping("/ls")
    public AjaxResult editLs(@RequestBody FsCaseProgressCourt fsCaseProgressCourt) {
        if (StringUtils.isNotBlank(fsCaseProgressCourt.getFileUrls())) {
            String[] urls = fsCaseProgressCourt.getFileUrls().split(",");
            for (int i = 0; i < urls.length; i++) {
                String url = urls[i];
                String fileName = getFileNameByUrl(url);
                FsCaseProgressFile file = new FsCaseProgressFile();
                file.setProcessId(fsCaseProgressCourt.getProcessId());
                file.setType(1);
                file.setName(fileName);
                file.setOosUrl(url);
                fsCaseProgressFileService.insertFsCaseProgressFile(file);
            }
        }
        FsCaseProgressCourt progressCourt = fsCaseProgressCourtService.selectFsCaseProgressCourtById(fsCaseProgressCourt.getId());
        progressCourt.setDlls(fsCaseProgressCourt.getDlls());
        progressCourt.setDllssjh(fsCaseProgressCourt.getDllssjh());
        return toAjax(fsCaseProgressCourtService.updateFsCaseProgressCourt(progressCourt));
    }

    /**
     * 修改案件进展开庭
     */
    @PreAuthorize("@ss.hasPermi('fs:case:edit')")
    @Log(title = "案件进展开庭", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FsCaseProgressCourt fsCaseProgressCourt) {
        if (StringUtils.isNotBlank(fsCaseProgressCourt.getFileUrls())) {
            String[] urls = fsCaseProgressCourt.getFileUrls().split(",");
            for (int i = 0; i < urls.length; i++) {
                String url = urls[i];
                String fileName = getFileNameByUrl(url);
                FsCaseProgressFile file = new FsCaseProgressFile();
                file.setProcessId(fsCaseProgressCourt.getProcessId());
                file.setType(2);
                file.setName(fileName);
                file.setOosUrl(url);
                fsCaseProgressFileService.insertFsCaseProgressFile(file);
            }
        }
        return toAjax(fsCaseProgressCourtService.updateFsCaseProgressCourt(fsCaseProgressCourt));
    }

    /**
     * 修改案件进展开庭
     */
    @PreAuthorize("@ss.hasPermi('fs:case:edit')")
    @Log(title = "案件进展开庭", businessType = BusinessType.UPDATE)
    @PutMapping("/zjzb")
    public AjaxResult editZjzb(@RequestBody FsCaseProgressCourt fsCaseProgressCourt) {
        FsCaseProgressCourt progressCourt = fsCaseProgressCourtService.selectFsCaseProgressCourtById(fsCaseProgressCourt.getId());
        progressCourt.setZjzb(1);
        return toAjax(fsCaseProgressCourtService.updateFsCaseProgressCourt(progressCourt));
    }

    /**
     * 删除案件进展开庭
     */
    @PreAuthorize("@ss.hasPermi('fs:case:remove')")
    @Log(title = "案件进展开庭", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(fsCaseProgressCourtService.deleteFsCaseProgressCourtByIds(ids));
    }

    /**
     * 获取案件进展开庭日历
     */
    @PreAuthorize("@ss.hasPermi('fs:case:query')")
    @GetMapping(value = "/rl")
    public AjaxResult getRl() {
        List<FsCaseProgressCourt> progressCourts = fsCaseProgressCourtService.selectFsCaseProgressCourtList(new FsCaseProgressCourt());
        Map<String, List<FsCaseKT>> map = new HashMap<>();
        List<FsCaseKT> kts = new ArrayList<>();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < progressCourts.size(); i++) {
            FsCaseProgressCourt pc = progressCourts.get(i);
            FsCase fsCase = fsCaseService.selectFsCaseById(pc.getCaseId());
            FsCaseKT kt = new FsCaseKT();
            kt.setId(pc.getId());
            kt.setAh(pc.getAh());
            kt.setFymc(pc.getFymc());
            kt.setFt(pc.getFt());
            kt.setAjmc(fsCase.getAjmc());
            kt.setTime(pc.getKtsj());
            kt.setKtfs(pc.getKtfs());
            Date ktrq = pc.getKtrq();
            String day = df.format(ktrq);
            kt.setDay(day);
            if (map.get(day) != null) {
                kts = map.get(day);
            }
            kts.add(kt);
            map.put(day, kts);
        }
        SortListUtil<FsCaseKT> ktSort = new SortListUtil<>();
        List<Map> result = new ArrayList<>();
        for (String day : map.keySet()) {
            kts = map.get(day);
            ktSort.Sort(kts, "getTime", "asc");
            Map dayMap = new LinkedHashMap();
            dayMap.put("day", day);
            dayMap.put("data", kts);
            result.add(dayMap);
        }
        return success(result);
    }
}
